#pragma once
#include"Common.h"
#include"ThreadCache.h"
#include"PageCache.h"
#include"ObjectPool.h"

static void* ConcurrentAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		size_t alignsize = sizeclass::Roundup(size);
		size_t kpage = alignsize >> PAGE_SHIFT;
		PageCache::getinstance()->_pagemtx.lock();
		Span* span = PageCache::getinstance()->newspan(kpage);
		span->usesize = size;
		PageCache::getinstance()->_pagemtx.unlock();

		void* ptr = (void*)(span->_pageid << PAGE_SHIFT);

		return ptr;
	}
	else
	{
		if (pTLSThreadCache == nullptr)
		{
			static objectpool<ThreadCache> tcpool;
			pTLSThreadCache = tcpool.NEW();
		}

		//cout << std::this_thread::get_id() << ":" << pTLSThreadCache << endl;

		return pTLSThreadCache->Allocate(size);
	}
	
}

static void ConcurrentFree(void* ptr)
{
	Span* span = PageCache::getinstance()->MapObjectToSpan(ptr);
	size_t size = span->usesize;
	if (size > MAXBYTE)
	{
		
		PageCache::getinstance()->_pagemtx.lock();
		PageCache::getinstance()->ReleaseSpanToPageCache(span);
		PageCache::getinstance()->_pagemtx.unlock();

	}
	else
	{
		assert(pTLSThreadCache);
		pTLSThreadCache->Deallocate(ptr, size);
	}
}